package com.qinker.robot.hook.aio;

import com.qinker.robot.common.model.BaseRequest;
import com.sky.xposed.common.util.Alog;

import org.smartboot.ioc.transport.NioQuickClient;
import org.smartboot.ioc.transport.NioSession;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutionException;

/**
 * socket客户端
 * 连接QINKER机器人服务端
 * Created by Irany 2019/10/28 0028 21:38
 */
public class ClientStart {

    private static String host = "test.qinker.com";

    private static Integer port = 9527;


    private static NioSession<String> session;


    public static NioSession getSession() throws InterruptedException, ExecutionException, IOException {
        if (session == null || session.isInvalid()) {
            synchronized (ClientStart.class) {
                if (session == null || session.isInvalid()) {
                    start();
                }
            }
        }
        return session;
    }

    public ClientStart() {

    }

    public static void start() {
        Alog.i("[机器人服务端连接中...]");
        NioQuickClient<String> client = new NioQuickClient<>(host, port, new ClientStringProtocol(), new ClientProcessor());
        session = client.start();
        Alog.i("[机器人服务端已连接]");
    }


    /**
     * 发送消息给服务端
     */
    public static void send(BaseRequest request) {
        try {
            String body = request.toJson();
            writeInt(body.getBytes().length);
            session.write(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void writeInt(int v) throws IOException {
        byte[] result = new byte[4];
        result[0] = (byte) ((v >> 24) & 0xFF);
        result[1] = (byte) ((v >> 16) & 0xFF);
        result[2] = (byte) ((v >> 8) & 0xFF);
        result[3] = (byte) (v & 0xFF);
        ByteBuffer lengthBuffer = ByteBuffer.allocate(result.length + 1);
        lengthBuffer.put(result);
        lengthBuffer.flip();
        session.write(lengthBuffer);
    }

    public static void main(String[] args) {
       ClientStart.start();
    }
}
